/*
	Copyright 2010-2012 Tommaso Previero
	
	This file is part of TeXdocGraphic.

	TeXdocGraphic is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	TeXdocGraphic is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with TeXdocGraphic.  If not, see <http://www.gnu.org/licenses/>.
	
	Created:		12/05/2012

*/

package it.texdocgraphic.interpreter;

import it.texdocgraphic.logger.SimpleLogger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TexdocOutputInterpreter implements Iterator<TexdocResult> {
	private static final String TEXDOC_PATTERN_PROPERTY_KEY = "texdoc.pattern";
	
	private Pattern currentPattern = Pattern.compile("^[a-zA-Z]+[\\s]*(-?[0-9]+\\.?[0-9]*)[\\s]*([^\\s]*)[\\s]*?(.*)?$", Pattern.MULTILINE);
	private Matcher currentMatcher = null;

	public TexdocOutputInterpreter() {
		//if found some user-defined pattern load and use it
		String homeDir = System.getProperty("user.home");
		
		Properties tgProp = new Properties();
		FileInputStream in = null;
		try {
			in = new FileInputStream(homeDir + File.separator + ".tg" + File.separator + "tg.properties");
		} catch (FileNotFoundException fnfe) {/*no user defaults*/}
		
		if(in != null) {
			try {
				tgProp.load(in);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			if(tgProp.containsKey(TEXDOC_PATTERN_PROPERTY_KEY)) {
				currentPattern = Pattern.compile(tgProp.getProperty(TEXDOC_PATTERN_PROPERTY_KEY), Pattern.MULTILINE);
			}
		}
	}
	
	public void executeSearch(String searchString) {
		//execute the search
		String texdocOutputString = _doSearch(searchString);
		//then begin to parse the output
		this.currentMatcher = currentPattern.matcher(texdocOutputString);
	}

	public boolean hasNext() {
		if(currentMatcher != null) {
			return currentMatcher.find();
		}
		return false;
	}
	
	public TexdocResult next() {
		//parse the currentMatcher.group() into a TexdocResult and return that
		try {
			if(currentMatcher.groupCount() >= 2) {
				TexdocResult toReturn = new TexdocResult();
				toReturn.setFilePath(currentMatcher.group(2).trim());
				toReturn.setPoints(Double.parseDouble(currentMatcher.group(1).trim()));
				if(currentMatcher.groupCount() == 3) {
					toReturn.setInfo(currentMatcher.group(3).trim());
				}
				return toReturn;
			}
		} catch (Exception e) {
			return null;
		}
		return null;
	}

	public void remove() {
		//actually there's no need to remove anything
		//this method will never be used
	}
	
	private String _doSearch(String searchString) {
		String output = "";
		List<String> command = Arrays.asList(new String[] {"texdoc", "-s", "-M", searchString});
		ProcessBuilder pb = new ProcessBuilder(command);
		try {
			Process process = pb.start();
			InputStream is = process.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String read = null;
			while((read = br.readLine()) != null) {
				//while there's something in the output
				output += read + "\n\r";
			}
			br.close();
			is.close();
		} catch (IOException e) {
			SimpleLogger.log(e.getMessage());
		}
		
		return output;
	}
}
